import { ref } from 'vue'
import { defineStore } from 'pinia'
import { removeToken, setToken } from '@/utils/auth'
import { login, logout } from '@/api/login'
import { encrypt } from '@/utils/encrypt'
export const useUserStore = defineStore('user', () => {
  const user = ref({})

  function LoginOut() {
    return new Promise<true | void>((resolve, rejects) => {
      logout()
        .then((result) => {
          if (result.code == 200) {
            removeToken()
            resolve(true)
          }
        })
        .catch((err) => {
          rejects(err)
        })
    })
  }

  function Login(account: string, password: string) {
    return new Promise<boolean>((resolve, reject) => {
      login({ accountName: account, password: encrypt(password) }).then((res) => {
        if (res.code != 200) {
          reject()
        } else {
          setToken(res.data.tokenValue)
          user.value = res.data
          resolve(true)
        }
      })
    })
  }

  return { user, LoginOut, Login }
})
